package com.gao.a_buffer.a;

import org.junit.Test;

import java.nio.ByteBuffer;

/**
 * @author gao
 * @time 2020/06/18 09:52:46
 */
public class App {


    // 测试： 如何创建一个ByteBuffer缓冲区对象，以及position、limit、capacity的概念
    @Test
    public void test() {
        ByteBuffer buf = ByteBuffer.allocate(10);

        System.out.println("limit\t" + buf.limit());
        System.out.println("position\t" + buf.position());
        System.out.println("capacity\t" + buf.capacity());
        System.out.println("mark\t" + buf.mark());
        System.out.println("content\t" + new String(buf.array()));
    }

    // 测试：ByteBuffer的put方法的使用
    @Test
    public void test2() {
        // 创建一个缓冲区
        ByteBuffer buf = ByteBuffer.allocate(10);

        buf.put("spirit".getBytes());

        System.out.println("limit\t" + buf.limit());
        System.out.println("position\t" + buf.position());
        System.out.println("capacity\t" + buf.capacity());
        System.out.println("mark\t" + buf.mark());
        System.out.println("content\t" + new String(buf.array()));
    }

    // 测试：多次调用ByteBuffer的put方法，会向缓冲区中连续写入内容。
    @Test
    public void test3() {
        ByteBuffer buf = ByteBuffer.allocate(10);

        buf.put("spirit".getBytes());

        System.out.println("limit\t" + buf.limit());
        System.out.println("position\t" + buf.position());
        System.out.println("capacity\t" + buf.capacity());
        System.out.println("mark\t" + buf.mark());
        System.out.println("content\t" + new String(buf.array()));

        System.out.println("======================================================");

        // 续写
        buf.put("!!!!".getBytes());

        System.out.println("limit\t" + buf.limit());
        System.out.println("position\t" + buf.position());
        System.out.println("capacity\t" + buf.capacity());
        System.out.println("mark\t" + buf.mark());
        System.out.println("content\t" + new String(buf.array()));
    }

    // 测试：在buf中已经写满数据的前提下，尝试再继续向buf中写入数据，就会抛出异常
    // 简单来说，就是当position的值要超过limit的时候，就会报错
    // 总之，我们无法读写limit后的数据
    @Test
    public void test4() {
        // 创建一个缓冲区
        ByteBuffer buf = ByteBuffer.allocate(10);

        buf.put("spirit!!!!".getBytes());
        System.out.println("I am here");
        // 以下代码在运行时，会抛出java.nio.BufferOverflowException
        buf.put("~".getBytes());
        System.out.println("Where is she");
    }
}
